package com.yunysha.struts.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.yunysha.beans.UserBean;
import com.yunysha.constants.YunyshaConstants;
import com.yunysha.controller.YunyshaController;
import com.yunysha.struts.actionform.UserMasterForm;

public class UserMasterAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String forward = null;
		
		UserMasterForm uForm = (UserMasterForm) form;
		
		YunyshaController yController = new YunyshaController();
		
		if(request.getParameter("edit")!=null){
			
			uForm.setIsCreate("Y");
			String userId = request.getParameter("edit");
			
			uForm.setUserId(0);
			uForm.setUserFirstName("");
			uForm.setUserMiddleName("");
			uForm.setUserLastName("");
			uForm.setUserMobile("");
			uForm.setUserEmail("");
			uForm.setUserLoginId("");
			yController.retreiveUserDetails(userId, uForm);
		} else {
			uForm.setIsCreate("N");
		}
		
		ArrayList<UserBean> userList = yController.retrieveAllUsers(uForm.getSearchUserName(),uForm.getSearchUserMobile(),
				uForm.getSearchUserEmail(),uForm.getPageOffSet());
		
		int numberOfRecords = userList.size();
		int numberOfPages = numberOfRecords%10==0 ? numberOfRecords/10 : (numberOfRecords/10)+1;
		
		uForm.setSearchList(userList);	
		uForm.setIsError("");
		uForm.setErrorMessage("");
		uForm.setNumberOfPages(numberOfPages);
		uForm.setNumberOfRecords(numberOfRecords);
		
		forward = YunyshaConstants.SUCCESS;
		
		return mapping.findForward(forward);
	}
}
